// translate router.meta.title, be used in breadcrumb sidebar tagsview

import http from '../axios/http';
import i18n from '../lang/index.js'

/**
 * 根据 路由name 获取多语言对应的 路由名
 * @param title
 * @returns {*}
 */
export function generateTitle(title) {
    // const hasKey = this.$te('route.' + title)
    // console.log(hasKey)
    const translatedTitle = this.$t('route.' + title) // $t :this method from vue-i18n, inject in @/lang/index.js
    // console.log(translatedTitle)

    // if (hasKey) {
        return translatedTitle
    // }
    // return title
}

/**
 * 多语言获取对应关系
 * @param lang
 * @param sort
 * @param pageCode
 * @param callback
 */
export function getLangLocale(lang, sort, pageCode, callback) {
    // console.log("getLangLocale: lang:" + lang + ", sort:" + sort + ", pageCode:" + pageCode);

    // 拼装localStorage的key
    let key = "bbc" + lang + "_" + sort + (pageCode ? "_" + pageCode : "");

    //获取localStorage
    let langLocale = localStorage.getItem(key);
    // console.log("langLocale: " + langLocale);
    if (langLocale && langLocale !== "{}") {
        //挂载多语言数据到i18n
        i18n._vm.messages[lang] = Object.assign(JSON.parse(langLocale), i18n.messages[lang]);
        // console.log("i18n.messages[lang]: " + JSON.stringify(i18n.messages[lang]));

        //回调 处理同步请求
        callback ? callback() : null
        return;
    }

    //没有localStorage，则请求接口加载数据
    let params = {
        lang: lang,
        sort: sort
    }

    if (pageCode) {
        params.pageCode = pageCode;
    }

    http.get("api/language", {params: params}).then(response => {
        // console.log("response: " + JSON.stringify(response));
        if (JSON.stringify(response) !== "{}") {
            //存入localStorage
            localStorage.setItem(key, JSON.stringify(response));

            //挂载多语言数据到i18n
            i18n._vm.messages[lang] = Object.assign(response, i18n.messages[lang]);
            // console.log(i18n.messages[lang]);
        }
        //回调 处理同步请求
        callback ? callback() : null
    })
}
